#!/bin/bash
# File Name: skip_mysql_repl_error_for_gtid.sh
# Author: moshan
# mail: mo_shan@yeah.net
# Created Time: 2019-04-18 09:05:42
# Function: 
#########################################################################
debug="${1}"
mysql_admin_user="moshan"
mysql_admin_pass="xxxxxx"
mysql_host="192.168.x.x"
mysql_port="3306"
mysql_comm="mysql -u${mysql_admin_user} -p${mysql_admin_pass} -h${mysql_host} -P${mysql_port}"
gtid_str="38f8425e-9182-5934-b32a-7e4317fe4a04"
log_file="${HOME}/info.log"
echo -e "\033[32m[$(date "+%F %H:%M:%S")] [INFO] log file \"${log_file}\"\033[0m"
while :
do
    error_gtid_num=$(${mysql_comm} -e "show slave status\\G"|grep "Worker .* failed executing transaction"|tail -1|awk -F"${gtid_str}" '{print $2}'|awk -F"'" '{print $1}')
    [ "$(wc -l < gtid)x" == "0x" ] && continue
    if [ "${debug}x" == "x" ]
    then
        ${mysql_comm} -e "show slave status\\G"
        skip_befor_binlog=$(${mysql_comm} -e "show slave status\\G" 2>/dev/null|grep -v "Relay_Master_Log_File:"|grep "Master_Log_File:"|awk '{print $2}')
        skip_befor_pos=$(${mysql_comm} -e "show slave status\\G" 2>/dev/null|grep "Read_Master_Log_Pos:"|awk '{print $2}')
        skip_befor_gtid_num=$(${mysql_comm} -e "show master status\\G" 2>/dev/null|grep -A 1000 "Executed_Gtid_Set:"|sed 's/Executed_Gtid_Set: //'|sort|tr -d "\n")
        echo -e "\033[32m[$(date "+%F %H:%M:%S")] [INFO] skip_befor_binlog_pos:${skip_befor_binlog}:${skip_befor_pos}\033[0m"|tee -a ${log_file}
        echo -e "\033[32m[$(date "+%F %H:%M:%S")] [INFO] skip_befor_gtid_num:${skip_befor_gtid_num}\033[0m"|tee -a ${log_file}
        echo "set gtid_next='${gtid_str}:${error_gtid_num}';begin;commit;SET SESSION GTID_NEXT = AUTOMATIC;start slave;"|${mysql_comm}
        ${mysql_comm} -e "show slave status\\G"
    elif [ "${debug}x" == "debugx" ]
    then
        echo "stop slave;set gtid_next='${gtid_str}:${error_gtid_num}';begin;commit;SET SESSION GTID_NEXT = AUTOMATIC;start slave;"
        exit
    fi
done
